package org.jfk.tomcatbell;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;

import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;

public class TomcatDetector extends Thread{

	@Override
	public void run() {
		while(true){
			Timestamp t = new Timestamp(System.currentTimeMillis());
			System.out.println();
			System.out.println(t + " detector running...");
			
			Prop prop = PropKit.use("bell.properties");
			
			

			String group = prop.get("tomcat_group");
			int check_interval = prop.getInt("tomcat_check_interval");

			String tm[] = group.split(",");
			
			PrintStream prtStrm = System.out;

			for (int i = 0; tm != null && i < tm.length; i++) {
				String check_url = prop.get("tomcat." + tm[i] + "." + "check_url");
				if (check_url == null) {
					continue;
				}

				System.out.println("tomcat checker is " + tm[i]);

				int timeout = prop.getInt("tomcat." + tm[i] + "." + "timeout");
				String start_cmd = prop.get("tomcat." + tm[i] + "." + "start_cmd");
				String stop_cmd = prop.get("tomcat." + tm[i] + "." + "stop_cmd");
				
				
				boolean check_result = check(check_url,timeout);
				System.out.println("tomcat." + tm[i] + "." + "check result = " + check_result);
				
				if (!check_result){
		            System.out.println("测试连接失败,重启 tomcat." + tm[i]);  
					TomcatBell tb = new TomcatBell(stop_cmd,start_cmd);
					tb.start();
				}
			}
			
			try {
				Thread.sleep(check_interval*1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static boolean check(String check_url,int timeout) {

		URL url = null;
		try {
			url = new URL(check_url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			URLConnection urlConn = url.openConnection();
			urlConn.setReadTimeout(timeout*1000);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					urlConn.getInputStream())); // 实例化输入流，并获取网页代码
			String s;
			while ((s = reader.readLine()) != null) {
				//System.out.println(s);
				return true;
			}
		} catch (Exception e) {
			//e.printStackTrace();
			return false;
		}

		return false;
	}	
}
